/**
 * 
 */
package com.huawei.esdk.uc.sametime.services;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

import com.huawei.esdk.uc.jna.UCService;
import com.huawei.esdk.uc.jna.Constants.CallHistoryType;
import com.huawei.esdk.uc.jna.Constants.UCServiceRetvCode;
import com.huawei.esdk.uc.jna.struct.STCallHistroyData;
import com.huawei.esdk.uc.jna.struct.STCallHistroyItem;
import com.huawei.esdk.uc.jna.struct.STConfPartData;
import com.huawei.esdk.uc.jna.struct.STConfPartItem;
import com.huawei.esdk.uc.jna.struct.STConvHistroyData;
import com.huawei.esdk.uc.jna.struct.STConvHistroyItem;
import com.huawei.esdk.uc.jna.util.StringUtil;
import com.huawei.esdk.uc.sametime.EsdkPluginActivator;
import com.huawei.esdk.uc.sametime.ConstantsDefines.CallMode;
import com.huawei.esdk.uc.sametime.ConstantsDefines.CallStatus;
import com.huawei.esdk.uc.sametime.models.ConfHistItem;
import com.huawei.esdk.uc.sametime.models.Participant;
import com.huawei.esdk.uc.sametime.models.ParticipantList;
import com.huawei.esdk.uc.sametime.util.ImageFactory;
import com.ibm.collaboration.realtime.people.Person;

/**
 * @author y00175154
 * 
 */
public class UCHistoryService
{
    private static Logger logger = Logger.getLogger(UCHistoryService.class);

    /**
     * 插入通话历史记录
     * @param account
     * @param duration 通话时间，未接通为-1.
     * @return
     */
    public static int insertCallHistory(String account, String num, int duration)
    {
        logger.debug("callMode = " + UCCallService.getCallMode()
                + ", callStatus = " + UCCallService.getCallStatus());
        int historyCallType = CallHistoryType.HISTORY_CALL_DIALED;

        if (CallMode.callIn == UCCallService.getCallMode())
        {
            if (CallStatus.connected == UCCallService.getCallStatus())
            {
                historyCallType = CallHistoryType.HISTORY_CALL_ANSWERED;
            }
            else
            {
                historyCallType = CallHistoryType.HISTORY_CALL_MISSED;
            }
        }
        if (CallStatus.connected != UCCallService.getCallStatus())
        {
            duration = -1;
        }
        String name = "";
        if (null != EsdkPluginActivator.getDefault())
        {
            Person person = EsdkPluginActivator.getDefault().getPersonMap()
                    .get(account);
            if (null != person)
            {
                name = person.getDisplayName();
            }
        }
        if (StringUtil.isEmptyStr(name))
        {
            name = account;
        }
        
        if(StringUtil.isEmptyStr(num))
        {
            num = account;
        }
        
        logger.debug("insertCallHistory | name = " + name + ", num = "
                + account + ", duration = " + duration);
        return UCService.getInstance().UC_SDK_InsertCallHistory(
                historyCallType, num, name, duration);
    }

    /**
     * 获取呼叫历史记录
     * @param callType 参考 CallHistoryType
     * @param fromIndex
     * @param toIndex
     * @return
     */
    public static List<STCallHistroyItem> getCallHistData(int callType,
            int fromIndex, int toIndex)
    {
        logger.debug("getCallHistData enter");
        List<STCallHistroyItem> callHistoryList = new ArrayList<STCallHistroyItem>();
        STCallHistroyItem tempCallHistoryItem = null;
        // 这里调用UC SDK 获取本地呼叫历史记录数据的服务接口
        STCallHistroyData callHistroyData = UCService.getInstance()
                .UC_SDK_QueryCallHistory(callType, fromIndex, toIndex);
        if (null != callHistroyData)
        {
            STCallHistroyItem[] histroyItems = callHistroyData.stCallHistory;
            int size = Math.min(callHistroyData.iTotal, histroyItems.length);
            for (int i = 0; i < size; i++)
            {
                tempCallHistoryItem = histroyItems[i];
                // logger
                // .debug("getCallHistData | callname is: "
                // + StringUtil
                // .bytesToUTF8String(tempCallHistoryItem.callName));
                callHistoryList.add(tempCallHistoryItem);
            }
        }
        logger.debug("getCallHistData end");
        return callHistoryList;
    }

    /**
     * 插入会议历史记录
     * @param leaderAccount 主持人账号
     * @param leaderName 主持人名字
     * @param duration 会议持续时间，未接通为-1.
     * @param convMembers 与会人列表
     */
    public static void insertConvHistory(String leaderAccount,
            String leaderName, int duration, ParticipantList convMembers)
    {
        logger.debug("callMode = " + UCCallService.getCallMode());

        logger.debug("insertConvHistory | leaderAccount = " + leaderAccount
                + ", leaderName = " + leaderName + ", duration = " + duration
                + ", convMembers.size = " + convMembers.size());

        if (!StringUtil.isEmptyStr(leaderName))
        {
            leaderAccount = leaderName;
        }

        String historyConvID = UCService.getInstance()
                .UC_SDK_InsertConvHistory(leaderAccount, leaderName, duration);
        if (StringUtil.isEmptyStr(historyConvID))
        {
            return;
        }
        historyConvID = historyConvID.trim();

        String partAccount = "";
        String partName = "";
        for (Participant participant : convMembers.getparticipants())
        {
            partAccount = participant.getUcAccount();
            partName = participant.getNickname();

            // logger.debug("InsertConvHistoryPart | historyConvID = "
            // + historyConvID + ", partAccount = " + partAccount
            // + ", partName = " + partName);
            if (!StringUtil.isEmptyStr(partName))
            {
                partAccount = partName;
            }
            UCService.getInstance().UC_SDK_InsertConvHistoryPart(historyConvID,
                    partAccount, partName);
        }
    }

    public static List<ConfHistItem> getConfHistData(int fromIndex, int toIndex)
    {
        logger.debug("getConfHistData enter");
        List<ConfHistItem> convHistoryList = new ArrayList<ConfHistItem>();
        // 这里调用UC SDK 获取本地即时会议历史记录数据的服务接口
        STConvHistroyData convHistroyData = UCService.getInstance()
                .UC_SDK_QueryConvHistory(fromIndex, toIndex);
        if (null != convHistroyData)
        {
            STConvHistroyItem[] histroyItems = convHistroyData.stConvHistory;

            STConvHistroyItem histroyItem;
            ConfHistItem confHistItem;

            int size = Math.min(convHistroyData.iTotal, histroyItems.length);
            for (int i = 0; i < size; i++)
            {
                histroyItem = histroyItems[i];
                confHistItem = new ConfHistItem();
                confHistItem.setConvHistroyItem(histroyItem);

                String convID = StringUtil.bytesToString(histroyItem.convID);

                // logger
                // .debug("getConfHistData | convID = "
                // + convID
                // + ", compereAccount = "
                // + StringUtil
                // .bytesToUTF8String(histroyItem.compereAccount)
                // + ", compereName = "
                // + StringUtil
                // .bytesToUTF8String(histroyItem.compereName));
                confHistItem.addConfPartItems(getHistoryPartByID(convID, 0,
                        histroyItem.partcipantNum));

                convHistoryList.add(confHistItem);
            }
        }
        logger.debug("getConfHistData end");
        return convHistoryList;
    }

    private static List<STConfPartItem> getHistoryPartByID(String convID,
            int fromIndex, int toIndex)
    {
        logger.debug("getHistoryPartByID | convID = " + convID);
        List<STConfPartItem> list = new ArrayList<STConfPartItem>();
        STConfPartData confPartData = UCService.getInstance()
                .UC_SDK_QueryHisConvPartByID(convID, fromIndex, toIndex);
        if (null != confPartData)
        {
            STConfPartItem[] confPartItems = confPartData.stConfPart;
            int size = Math.min(confPartData.partNum, confPartItems.length);
            for (int i = 0; i < size; i++)
            {
                // logger
                // .debug("getHistoryPartByID | convID = "
                // + convID
                // + ", partAccount = "
                // + StringUtil
                // .bytesToUTF8String(confPartItems[i].partAccount)
                // + ", "
                // + StringUtil
                // .bytesToUTF8String(confPartItems[i].partName));
                list.add(confPartItems[i]);
            }
        }
        return list;
    }

    public static boolean deleteCallHistData(int iRcdID)
    {
        // 这里调用UC SDK 删除本地呼叫历史记录数据的服务接口
        int ret = UCService.getInstance().UC_SDK_DeleteCallHistory(iRcdID);
        if (UCServiceRetvCode.UC_SDK_Success == ret)
        {
            return true;
        }
        return false;
    }

    public static boolean deleteConfHistData(String pConvID)
    {
        // 这里调用UC SDK 删除本地即时会议历史记录数据的服务接口
        int ret = UCService.getInstance().UC_SDK_DeleteConvHistory(pConvID);
        if (UCServiceRetvCode.UC_SDK_Success == ret)
        {
            return true;
        }
        return false;
    }

    public static Image getHistoryTypeImage(int callType)
    {
        Image typeImage;
        if (CallHistoryType.HISTORY_CALL_MISSED == callType)
        {
            typeImage = getImage(ImageFactory.ICON_HISTORY_MISSED);
        }
        else if (CallHistoryType.HISTORY_CALL_ANSWERED == callType)
        {
            typeImage = getImage(ImageFactory.ICON_HISTORY_ANSWERED);
        }
        else
        {
            typeImage = getImage(ImageFactory.ICON_HISTORY_DIALED);
        }

        return typeImage;
    }

    private static Image getImage(String imgPath)
    {
        return ImageFactory.loadImage(Display.getCurrent(), imgPath);
    }

}
